package com.lei.sqlGoodsJsp.servlet;

import java.io.IOException;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lei.sqlGoodsJsp.constant.UserConstant;
import com.lei.sqlGoodsJsp.entity.LoginUserEntity;
import com.lei.sqlGoodsJsp.entity.Page;
import com.lei.sqlGoodsJsp.service.UserLoginServicePage;
import com.lei.sqlGoodsJsp.service.Impl.UserLoginServicePageImpl;

public class UserLoginServlet extends HttpServlet {
	static UserLoginServicePage userLoginService=new UserLoginServicePageImpl();
	private Long count = 1L;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		HttpSession session = req.getSession();
		if(req.getSession().getAttribute(UserConstant.USER_INFO)==null) {
			resp.sendRedirect("sql/userLogin.jsp");
			return;
		}
		String method = req.getParameter("method");
		System.out.println(method);
		if ("add".equals(method)) {
			add(req, resp);
			resirectList(resp);
		}else if ("list".equals(method)) {
			list(req,resp);
		} else {
			resirectList(resp);
		}
	}
	private void resirectList(HttpServletResponse res) throws IOException {
		res.sendRedirect("UserLoginServlet?method=list");
	}
	
	private void add(HttpServletRequest req, ServletResponse res) throws ServletException, IOException {
		String loginUser = req.getParameter("loginUser");
		String loginIp = req.getParameter("loginIp");
		String loginStatus=req.getParameter("loginStatus");
		LoginUserEntity user = new LoginUserEntity();
		user.setLoginUser(loginUser);
		user.setLoginIp(loginIp);
		user.setLoginStatus(loginStatus);
		userLoginService.add(user);
	}
	private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		req.setAttribute("user", ShopPage(req));
		req.getRequestDispatcher("sql/userLogin.jsp").forward(req, resp);
	}
	private Page<LoginUserEntity> ShopPage(HttpServletRequest req) throws ServletException, IOException {
		String currentPage = req.getParameter("currentPage");
		int intCurrentPage = Optional.ofNullable(currentPage).map(e -> Integer.parseInt(currentPage)).orElse(1);
		int pageSize = 3;
		return userLoginService.page(intCurrentPage, pageSize);
	}
}
